package com.ucap.weking.guangan.fragments;

import android.content.Intent;
import android.graphics.Color;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ucap.weking.guangan.Activitys.NewContentActivity;
import com.ucap.weking.guangan.R;
import com.ucap.weking.guangan.adapter.LIstAdapter;
import com.ucap.weking.guangan.base.BaseFragment;
import com.ucap.weking.guangan.bean.ListItemBean;
import com.ucap.weking.guangan.bean.TianQiBean;
import com.ucap.weking.guangan.dataUri.DataUri;
import com.ucap.weking.guangan.fragments.publicFragment.HomeContentPublic;
import com.ucap.weking.guangan.httpTools.HttpCallRequest;
import com.ucap.weking.guangan.modle.ItemModel;
import com.ucap.weking.guangan.views.LoadingListView;
import com.ucap.weking.guangan.views.MyToast;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by weking on 2017/10/17.
 * 便民服务
 */

public class HomeContent4 extends BaseFragment {
    @InjectView(R.id.lv_content)
    LoadingListView lvContent;
    @InjectView(R.id.srlRefresh)
    SwipeRefreshLayout srlRefresh;
    @InjectView(R.id.tv_is_null)
    TextView tvIsNull;
    private LIstAdapter adapter;
    private int numow = 1;//页面开始角标
    private int num = 10;//页面结束角标
    public String contentUri = DataUri.getBIAN_MING_XIN_XI();//页面数据地址
    public String contentName = "便民信息";//页面名称
    private View header;
    private TextView tvTxt;
    private TextView tvPm25;
    private TextView tvDegree;
    private TextView tvTemVis;
    private String[] images;
    private ImageView ivImageTianQi;

    public HomeContent4() {

    }

    @Override
    public void setData() {
        numow = 1;
        num = 10;
        final ArrayList<ItemModel> mData = new ArrayList<>();
        adapter = new LIstAdapter(mData);
        lvContent.setAdapter(adapter);
        getData(mData, numow, num);
        srlRefresh.setColorSchemeResources(R.color.colorPrimary);
        srlRefresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                numow = 1;
                num = 10;
                mData.clear();
                getData(mData, numow, num);//更新列表数据
                addHeadTianQi();//更新天气信息
            }
        });

        lvContent.setInterface(new LoadingListView.IloadListener() {
            @Override
            public void onLoad() {
                getData(mData, numow += 10, num += 10);
            }
        });
        lvContent.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                int index = position - 1;
                if (mData.size() > 0 && index > -1 && index <= mData.size())
                    startContentActivity(adapter.getItem(index).getContentUri());
            }
        });
        header = LayoutInflater.from(getContext()).inflate(R.layout.header_person_service, null);
        ivImageTianQi = (ImageView) header.findViewById(R.id.iv_bg_tian_image);
        images = new String[]{"https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510315674865&di=4c6f318820b1bbaa42cf0594e310bab5&imgtype=0&src=http%3A%2F%2Fwww.swcegroup.com%2Fhtml%2Fgcyj%2Fuploadfiles%2F150302%2F201503020938266521.jpg",
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510315674865&di=b746cffdf36846dd385aafb671f858d2&imgtype=0&src=http%3A%2F%2Fimgsrc.baidu.com%2Fimgad%2Fpic%2Fitem%2F42166d224f4a20a437b7b7fe9b529822720ed05a.jpg",
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510315674864&di=158bf19b1daa22aa6900468b22c7db16&imgtype=0&src=http%3A%2F%2Fwww.gata.gov.cn%2Fupload%2F2016%2F2%2F1455418355773.jpg",
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510316574997&di=9c26fdef02577273d276024e9b7404bc&imgtype=0&src=http%3A%2F%2Fp3.pccoo.cn%2Fbbs%2F20151125%2F2015112515293778145119.jpg",
                "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1510911392&di=e99a39708c97fc6c18dbaa3383bd1402&imgtype=jpg&er=1&src=http%3A%2F%2Fimg.mala.cn%2Fforum%2F201408%2F26%2F183724cbk1b8khkn8cxrbs.jpg",
                "http://pic3.newssc.org/upload/ori/20160112/1452565429252.jpg",
                "http://www.gata.gov.cn/upload/2015/11/1446803473955.jpg",
                "http://www.gata.gov.cn/upload/2017/3/1489392088087.jpg",
        };

        //天气
        tvTxt = (TextView) header.findViewById(R.id.tv_txt);
        //pm25
        tvPm25 = (TextView) header.findViewById(R.id.tv_pm25);
        //当前温度
        tvDegree = (TextView) header.findViewById(R.id.tv_degree);
        //最高最低温度
        tvTemVis = (TextView) header.findViewById(R.id.tv_tem_vis);
        addHeadTianQi();
    }

    int index = 0;

    private void addHeadTianQi() {
        HttpCallRequest.callRequest(DataUri.getTianQiUri(), new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            lvContent.removeHeaderView(header);
                            Gson gson = new Gson();
                            TianQiBean tianQiBean = gson.fromJson(body, TianQiBean.class);
                            TianQiBean.HeWeatherBean heWeatherBean = tianQiBean.getHeWeather().get(0);
                            tvTxt.setText(heWeatherBean.getNow().getCond().getTxt());
                            tvPm25.setText("pm2.5: " + heWeatherBean.getAqi().getCity().getPm25());
                            tvDegree.setText(heWeatherBean.getNow().getFl() + "℃");
                            tvTemVis.setText(heWeatherBean.getDaily_forecast().get(0).getTmp().getMin() + "℃/" + heWeatherBean.getDaily_forecast().get(0).getTmp().getMax() + "℃");
                            lvContent.addHeaderView(header);
                            Random random = new Random();
                            index = random.nextInt(images.length);//随机显示图片
                            Glide.with(getActivity()).load(images[index])
                                    .into(ivImageTianQi);
                        } catch (Exception e) {
                            lvContent.removeHeaderView(header);
                        }

                    }
                });

            }

            @Override
            public void onErr(Exception e) {

            }
        });


    }

    private void getData(final ArrayList<ItemModel> mData, final int startNum, int endNum) {
        if (startNum == 1)
            srlRefresh.setRefreshing(true);
        HttpCallRequest.callRequest(contentUri + "numtwo=" + startNum + "&num=" + endNum, new HttpCallRequest.OnCallListener() {
            @Override
            public void onRequest(final String body) {
                Log.i("number", "numow:  " + numow + " num: " + num);
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Gson gson = new Gson();
                        ListItemBean listItemBean = gson.fromJson(body, ListItemBean.class);
                        if (listItemBean != null) {
                            ArrayList<ItemModel> data = new ArrayList<>();
                            List<ListItemBean.RowsBean> rows2 = listItemBean.getRows();
                            if (rows2 != null && rows2.size() > 0) {
                                for (ListItemBean.RowsBean bean2 : rows2) {
                                    ItemModel model = new ItemModel(bean2.getTITLE(), bean2.getTIME(), bean2.getID());
                                    model.setImage(false);
                                    model.setImageId(bean2.getPATHANDURL());
                                    model.setContentUri(bean2.getURL());
                                    data.add(model);
                                }
                                mData.addAll(data);
                                adapter.notifyDataSetChanged();
                                srlRefresh.setRefreshing(false);
                                lvContent.loadComplete();
                                tvIsNull.setVisibility(View.GONE);
                            } else {
                                MyToast.showTrue(getContext(), "已加载全部！");
                                srlRefresh.setRefreshing(false);
                                lvContent.loadComplete();
                                tvIsNull.setVisibility(View.GONE);
                                if (numow > 1) {
                                    numow -= 10;
                                    num -= 10;
                                }
                            }
                        } else {
                            MyToast.showTrue(getContext(), "已加载全部！");
                            srlRefresh.setRefreshing(false);
                            lvContent.loadComplete();
                            tvIsNull.setVisibility(View.GONE);
                            if (numow > 1) {
                                numow -= 10;
                                num -= 10;
                            }
                        }


                    }
                });
            }

            @Override
            public void onErr(Exception e) {
                getActivity().runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        srlRefresh.setRefreshing(false);
                        lvContent.loadComplete();
                        adapter.notifyDataSetChanged();
                        if (numow > 1) {
                            numow -= 10;
                            num -= 10;
                        }
                        if (mData.size() < 1) {
                            tvIsNull.setVisibility(View.VISIBLE);
                        } else {
                            tvIsNull.setVisibility(View.GONE);
                            MyToast.showTrue(getContext(), "连接超时，请检查网路连接！");
                        }
                        Log.i("number", "err   numow:  " + numow + " num: " + num);
                    }
                });

            }
        });
    }

    public void startContentActivity(String uri) {
        Intent intent = new Intent(getActivity(), NewContentActivity.class);
        intent.putExtra("title", contentName);
        intent.putExtra("uri", uri);
        getActivity().startActivity(intent);

    }

    @Override
    public void intiView() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.frgament_content1_news, null);
        ButterKnife.inject(this, view);
        flContent.addView(view);
    }

}
